package com.lymei.core.modules.system.service.impl;

import com.lymei.core.modules.system.mapper.IRoleMapper;
import com.lymei.core.modules.system.mapper.IUserMapper;
import com.lymei.lib.po.system.UserDetailsImpl;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

/**
 * @author lymei
 * @title: UserDetailsServiceImpl
 * @projectName scui-admin
 * @description:
 * @date 2022/1/2015:39
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IRoleMapper roleMapper;

    /**
     * 模拟登录数据
     * @param account
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        var user = userMapper.selectUserByAccount(account);
        if (user == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        var roles = roleMapper.selectRolesByUserId(user.getId());
        user.setRole(roles.stream().map(t->t.getName()).collect(Collectors.toList()));
        return new UserDetailsImpl(user);
    }

}
